namespace TomatoBreak.Web
{
    using System;
    using System.Web.Mvc;

    using DataAccess;
    using DomainObjects;
    using Infrastructure;

    public class SessionController : ApplicationController
    {
        private readonly IRepository<User> repository;
        private readonly IFormsAuthentication formsAuthentication;

        public SessionController(IRepository<User> repository, IFormsAuthentication formsAuthentication)
        {
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }

            if (formsAuthentication == null)
            {
                throw new ArgumentNullException("formsAuthentication");
            }

            this.repository = repository;
            this.formsAuthentication = formsAuthentication;
        }

        public ActionResult Create(CreateSessionModel createModel)
        {
            if (createModel == null)
            {
                throw new ArgumentNullException("createModel");
            }

            if (!ModelState.IsValid)
            {
                return JsonModelStateErrors();
            }

            var user = repository.FindOne(u => u.Email == createModel.EmailOrUserName) ??
                       repository.FindOne(u => u.UserName == createModel.EmailOrUserName);

            if ((user == null) || user.Locked || !user.HasPassword(createModel.Password))
            {
                ModelState.AddModelError(string.Empty, ErrorMessages.SessionController_InvalidCredential);

                return JsonModelStateErrors();
            }

            formsAuthentication.SignIn(user.UserName, createModel.RememberMe);

            return HttpCreated();
        }

        [Authorize]
        public ActionResult Destroy()
        {
            formsAuthentication.SignOut();

            return HttpOk();
        }
    }
}